<template>
  <div class="purchase" ref="my_purchase">
    <div class="purchase_header">
      <div>
        <p>创建人:{{ detailData.createBy }}</p>
        <p>制单时间：{{ detailData.createTime }}</p>
        <p>采购编码：{{ detailData.purchaseOrderNo }}</p>
        <p>关联订单编码：{{ detailData.orderCode }}</p>
      </div>
      <el-button v-if="$route.query.auto" @click="handelClickBack">返回</el-button>
    </div>

    <!--  v-if="useRoutes.query.businessState == 3 ? false : true" -->
    <div class="purchase_supply_information">
      <div class="refuse_becuse">
        <p :style="{ color: colorStatus(detailData.businessState)[0] }">{{ showStatus(detailData.businessState) }}</p>
        <div class="refuse_becuse_info" v-if="detailData.showReject === 1">
          <p>拒绝原因：{{ detailData.commonRejectType || "-" }}</p>
          <p>备注：{{ detailData.commonRejectRemark || "-" }}</p>
        </div>
      </div>
      <div class="all-business" v-if="operationFlowInfo">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
          <el-tab-pane v-if="detailData.installConfirmInfo" label="安装确认记录" :name="1"></el-tab-pane>
          <el-tab-pane v-if="detailData.produceConfirmInfo" label="生产完成记录" :name="2"></el-tab-pane>
          <el-tab-pane v-if="detailData.distributeConfirmInfo" label="配送完成记录" :name="3"></el-tab-pane>
          <el-tab-pane v-if="detailData.selfPickupConfirmInfo" label="自提货完成记录" :name="4"></el-tab-pane>
        </el-tabs>
        <div class="all-business-content">
          <div class="content-remarks">
            备注描述：
            <div class="refuse-remark-info" v-html="operationFlowInfo.remark"></div>
          </div>
          <template v-if="operationFlowInfo.status == 2">
            <div class="refuse-info">
              <div class="reason">拒绝原因：{{ operationFlowInfo.refuseReason }}</div>
              <div class="refuse-remarks">
                备注描述：
                <div class="refuse-remark-info" v-html="operationFlowInfo.refuseRemark"></div>
              </div>
            </div>
          </template>
        </div>
      </div>
      <!--//新增图片视频 -->
      <!-- <div class="all-business">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="安装确认记录" :name="1"></el-tab-pane>
          <el-tab-pane label="生产完成记录" :name="2"></el-tab-pane>
          <el-tab-pane label="配送完成记录" :name="3"></el-tab-pane>
          <el-tab-pane label="自提货完成记录" :name="4"></el-tab-pane>
        </el-tabs>
        <div class="all-business-content">
          <div class="content-remarks">
            备注描述：
            <div class="refuse-remark-info">
              {{ operationFlowInfo.remark }}没错你是个明白人我明白你明白的意思我也是明白人明白人就应该明白我明白你明白事
            </div>
          </div>
          <div v-if="PicUrls.length > 0" class="picUrls_flex_countent">
            <div style="width: 69px; margin-right: 11px" v-for="item in videoUrls" :key="item">
              <video class="show-video" v-if="item" :src="item" controls></video>
            </div>
            <div style="width: 69px; margin-right: 11px" v-for="item in PicUrls" :key="item">
              <el-image :preview-src-list="[item]" :src="item" fit="fill" />
            </div>
          </div>
          <div class="refuse-info">
            <div class="reason">拒绝原因：{{ operationFlowInfo.refuseReason }}质量不过关2</div>
            <div class="refuse-remarks">
              备注描述：
              <div class="refuse-remark-info">{{ operationFlowInfo.refuseRemark }}啊实打实大苏打实打实打算</div>
            </div>
            <div v-if="PicUrls.length > 0" class="picUrls_flex_countent">
              <div style="width: 69px; margin-right: 11px" v-for="item in videoUrls" :key="item">
                <video class="show-video" v-if="item" :src="item" controls></video>
              </div>
              <div style="width: 56px; margin-right: 11px" v-for="item in PicUrls" :key="item">
                <el-image :preview-src-list="[item]" :src="item" fit="fill" />
              </div>
            </div>
          </div>
        </div>
      </div> -->
      <div class="purchase_supply_information_name">供应商信息</div>
      <div class="purchase_supply_information_message">
        <div>
          <p class="info_label">企业名称</p>
          <p>{{ detailData.anotherName }}</p>
        </div>
        <div>
          <p class="info_label">跟单人员</p>
          <p>{{ detailData.trackerName }}</p>
        </div>
        <div>
          <p class="info_label">跟单人电话</p>
          <p>{{ detailData.trackerTel }}</p>
        </div>
        <div>
          <p class="info_label">工厂地址</p>
          <p>{{ detailData.location }}</p>
        </div>
        <div>
          <p class="info_label">是否支持开票：</p>
          <p v-if="detailData.isSupportBilling == 1">
            {{ `支持开票(专票${detailData.specialTicket}%)(普票${detailData.ordinaryTicket}%)` }}
          </p>
          <p v-else>不支持开票</p>
        </div>
      </div>
    </div>
    <div class="purchase_commodity_information">
      <!--创建采购单列表 -->
      <p>商品信息</p>
      <el-table border style="width: 100%" class="jzt-table" :data="detailData.productDetailList">
        <!-- <el-table-column type="selection" width="55" /> -->
        <el-table-column prop="name" label="商品信息" width="480">
          <template #default="scope">
            <div class="sp_message ml30">
              <div>
                <img :src="scope.row.mainPicUrl" alt="" />
              </div>
              <div>
                <p
                  :class="{ 'jzt-cursor-point': scope.row.isCustom === 1 }"
                  @click="scope.row.isCustom === 1 ? toProdDetail(scope.row) : () => {}"
                >
                  {{ scope.row.productAliasName }}
                </p>
                <p>
                  {{ scope.skuSpecification }}
                </p>
                <p>{{ scope.row.skuSpecification }}</p>
                <p>SKU编码:{{ scope.row.skuCode }}</p>
                <p>ID:{{ scope.row.productId }}</p>
              </div>
              <div class="custom-fixed-icon" v-if="scope.row.isCustom === 1" @click="toProdDetail(scope.row)">
                <img src="@/assets/images/custom-icon.png" alt="" width="48" height="43" />
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="warrantyTime" label="商品质保日期" width="160">
          <template #default="{ row }">
            <span>{{ row.warrantyTime || 0 }}个月</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="224">
          <template #default="scope">
            <RemarkEditor v-model="scope.row.remark" :isEdit="false" />
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="供应单价" />
        <el-table-column prop="sendedNum" label="已发货数" />
        <el-table-column prop="sendedPartNum" label="已发货件数" />
        <el-table-column prop="commodityNum" label="数量"> </el-table-column>
        <el-table-column prop="totalPartNum" label="商品件数" />
        <template v-if="!isChainTenant">
          <el-table-column prop="measureDataRemark" label="测量数据反馈" />
          <el-table-column prop="discountRate" label="折扣率(%)"> </el-table-column>
          <el-table-column prop="discountAmount" label="折扣(元)">
            <template #default="scope">
              {{ Number(scope.row.discountAmount) }}
            </template>
          </el-table-column>
        </template>

        <el-table-column prop="actualAmount" label="采购价格"></el-table-column>
        <el-table-column prop="dealState" label="采购状态">
          <template #default="scope">
            <p
              class="cg_status"
              :style="{ color: colorStatus(scope.row.dealState)[0], background: colorStatus(scope.row.dealState)[1] }"
            >
              {{
                scope.row.dealState == 1
                  ? "待采购"
                  : scope.row.dealState == 2
                    ? "待接单 "
                    : scope.row.dealState == 3
                      ? "被拒绝"
                      : scope.row.dealState == 4
                        ? "待发货"
                        : scope.row.dealState == 5
                          ? "部分发货"
                          : scope.row.dealState == 6
                            ? "已发货"
                            : scope.row.dealState == 7
                              ? "待入库"
                              : scope.row.dealState == 8
                                ? "部分入库"
                                : scope.row.dealState == 9
                                  ? "已入库"
                                  : scope.row.dealState == 10
                                    ? "待出库"
                                    : scope.row.dealState == 11
                                      ? "部分出库"
                                      : scope.row.dealState == 12
                                        ? "已出库"
                                        : ""
              }}
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 底部表单信息 -->
    <div class="purchase_form">
      <div class="purchase_form-left">
        <el-form
          ref="ruleFormRef"
          style="max-width: 100%"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="预计生产周期" prop="expectedDeliveryTime">
            <template #label>
              <div>
                <p>预计生产周期</p>
                <p class="f12" style="line-height: 16px">(请填写天数)</p>
              </div>
            </template>
            <el-input-number
              class="input-number"
              placeholder="请填写天数"
              v-model="detailData.expectedDeliveryDays"
              :min="0"
              :controls="false"
              :disabled="true"
              style="width: 100%"
            />
            <div style="font-size: 12px; color: #86909c">预计生产周期根据付款节点关联，在对应节点配置生效后启动时间计算！</div>
          </el-form-item>
          <el-form-item label="收货类型" prop="">
            <el-radio-group :disabled="true" v-model="detailData.receivingType" class="ml-4">
              <el-radio value="1">收货仓库</el-radio>
              <el-radio value="2">直发客户</el-radio>
              <el-radio value="3"> 自提货</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="!isChainTenant">
            <el-form-item label="其他费用" prop="">
              <el-input-number
                :disabled="true"
                v-model="detailData.otherFee"
                :step="0.1"
                :precision="2"
                style="width: 100%"
                :controls="false"
                placeholder="请输入"
                @change="handelInputs"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="优惠金额" prop="">
              <el-input-number
                :disabled="true"
                v-model="detailData.discountAmount"
                :step="0.1"
                :precision="2"
                style="width: 100%"
                :controls="false"
                placeholder="请输入"
                @input="handelInputs1"
              ></el-input-number>
            </el-form-item>
          </template>

          <el-form-item label="本次应付金额">
            <template #label> <span style="color: #ff3333">*</span>本次应付金额 </template>
            <!-- <el-input v-model="getData.obj.currentPayableAmount" placeholder="" @input="handelInputsDiscountAmount"></el-input> -->
            <div style="display: flex; width: 100%">
              <el-input-number
                :disabled="detailData.canEditCurrentAmount !== 1 || detailData.businessState === 20"
                class="jzt-input-number"
                :min="0"
                :max="detailData.payableTotalAmount"
                :precision="2"
                controls-position="right"
                v-model.trim="detailData.currentPayableAmount"
                style="flex: 1; margin-right: 10px"
              ></el-input-number>
              <el-button type="primary" link @click="openPlanNodes"> 查看付款计划明细 </el-button>
            </div>
          </el-form-item>

          <el-form-item label="本次支付说明">
            <el-input
              v-model="detailData.currentPayableRemark"
              maxlength="200"
              placeholder="请输入"
              :disabled="detailData.businessState === 20"
            ></el-input>
          </el-form-item>
          <el-form-item label="收款账户选择">
            <el-select
              v-model="detailData.partnerAccountId"
              :disabled="detailData.businessState === 20"
              filterable
              :filter-method="filterZhList"
              placeholder="请输入收款账号或户号搜索"
              style="width: 100%"
            >
              <el-option
                v-for="item in zhList"
                :key="item.partnerAccountId"
                :label="
                  item.accountName
                    ? item.accountName + '：' + item.dictName + '：' + item.account
                    : item.dictName + '：' + item.account
                "
                :value="item.partnerAccountId"
              >
                <p v-if="item.accountName">{{ item.accountName + "：" + item.dictName + "：" + item.account }}</p>
                <p v-else>{{ item.dictName + "：" + item.account }}</p>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="订单说明" prop="">
            <!-- <el-input v-model="detailData.remark" :disabled="true" type="textarea" :max="120"></el-input> -->
            <template v-if="detailData.remark">
              <RemarkEditor v-model="detailData.remark" :isEdit="false" />
            </template>
            <template v-else>
              <RemarkEditor v-model="detailData.remark" :isEdit="false" />
            </template>
          </el-form-item>
          <el-form-item label="附件" prop="">
            <el-upload
              class="upload-demo"
              v-model:file-list="imgFileList"
              ref="uploadImg"
              :show-file-list="true"
              multiple
              :limit="10"
              list-type="text"
              :auto-upload="false"
              :disabled="true"
              :on-preview="handelOnPreview"
            >
              <template #trigger>
                <el-button class="update_btn" :disabled="imgFileList.length >= 10">
                  <el-icon class="f24" size="20"><Plus /></el-icon>
                </el-button>
                <p>点击上传</p>
              </template>
              <template #tip>
                <p class="f12 mt10" style="color: #86909c">支持doc/docx/pdf/jpg/png，最多上传10个。</p>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="是否开票" prop="isBusinessInvoice">
            <div style="display: flex; justify-content: space-between; width: 100%; background: #f5f7fa; padding: 0 20px">
              <el-radio-group v-model="detailData.isBusinessInvoice" disabled>
                <!-- <el-radio :value="1">开票</el-radio>
                <el-radio :value="0">不开票</el-radio> -->

                <div class="business-invoice">
                  <div class="is-business-invoice">
                    <el-radio :value="1">开票</el-radio>
                    <el-radio-group
                      class="radio-button"
                      v-model="detailData.invoiceType"
                      v-if="detailData.isBusinessInvoice === 1"
                      size="small"
                      disabled
                    >
                      <el-radio-button label="专票" :value="1" />
                      <el-radio-button label="普票" :value="2" />
                    </el-radio-group>
                  </div>
                  <el-radio :value="0">不开票</el-radio>
                </div>
              </el-radio-group>

              <div
                v-if="detailData.isSupportBilling == 0 && detailData.isBusinessInvoice === 1"
                style="color: #ff3333; font-size: 12px"
              >
                当前供应商不支持开票，请致电沟通后在提交采购单！
              </div>
            </div>
            <!-- <div class="warehouse_content" v-if="detailData.isBusinessInvoice === 1">
              <el-select v-model="detailData.invoiceType" placeholder="请选择开票类型">
                <el-option label="专票" :value="1" />
                <el-option label="普票" :value="2" />
              </el-select>
            </div> -->
          </el-form-item>
          <el-form-item label="发票附件" prop="isBusinessInvoice" v-if="detailData.isBusinessInvoice == 1">
            <div class="img-box" v-if="detailData.uploadInvoiceUrls && detailData.uploadInvoiceUrls.length > 0">
              <el-image
                class="img"
                v-for="(item, index) in detailData.uploadInvoiceUrls"
                :src="item"
                :preview-src-list="detailData.uploadInvoiceUrls"
                :initial-index="index"
                fit="cover"
                :key="item"
              />
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="purchase_form-right">
        <div v-if="detailData.businessState !== 9" class="purchase_form-right-top">
          <div class="header" v-if="detailData.businessState !== 4">
            <p>收货仓库</p>
            <el-select v-model="detailData.receivingWarehouseId" :disabled="true" @change="handelChangePutAway">
              <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </div>
          <p class="title">收货信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ detailData.receivingName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ detailData.receivingMobile }}</p>
          </div>
          <div>
            <p>
              收货地址:<el-icon style="vertical-align: middle" size="20" color="#ccc">
                <Edit />
              </el-icon>
            </p>
            <p>{{ detailData.receivingAreaDetail }} {{ detailData.receivingAddress }}</p>
          </div>
        </div>
        <div class="purchase_form-right-top">
          <p class="title">客户信息</p>
          <div>
            <p>姓名:</p>
            <p>{{ detailData.customerName }}</p>
          </div>
          <div>
            <p>电话:</p>
            <p>{{ detailData.customerMobileCode }}</p>
          </div>
          <div>
            <p>收货地址:</p>
            <p>{{ detailData.customerAddress }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="botton_btn" :style="{ width: footerWidth + 'px' }">
      <div class="left">
        <div class="mb16" v-if="!isChainTenant">
          <p>
            优惠金额：¥<span>{{ detailData.discountAmount }}</span>
          </p>
          <p>
            其他费用：¥<span>{{ detailData.otherFee }}</span>
          </p>
          <p>
            税额：¥<span>{{ detailData.invoiceAmount }}</span>
          </p>
        </div>
        <div>
          <p>
            商品总价：¥<span>{{ detailData.productTotalAmount }}</span>
          </p>
          <p>
            未付金额：<span>¥{{ detailData.remainTotalAmount }}</span>
          </p>
          <p>
            实付金额：<span>¥{{ detailData.actualTotalAmount }}</span>
          </p>
          <p>
            应付金额：<span>¥{{ detailData.payableTotalAmount }}</span>
          </p>
        </div>
      </div>
      <div class="right">
        <el-button v-if="detailData.isProduceConfirmState === 2" class="mr10" type="primary" plain @click="handleProduction(1)">
          生产完成
        </el-button>
        <el-button
          v-if="detailData.isDistributeConfirmState === 4"
          class="mr10"
          type="primary"
          plain
          @click="handleProduction(2)"
        >
          配送完成确认
        </el-button>
        <el-button v-if="detailData.isSelfPickupState === 3" class="mr10" type="primary" plain @click="handleProduction(3)">
          已完成提货
        </el-button>
        <el-button v-if="detailData.isInstallConfirmState === 2" class="mr10" type="primary" plain @click="handleProduction(4)">
          安装完成确认
        </el-button>
        <!-- showCancelButton===1，才有“撤销采购单”操作按钮 -->
        <el-button class="mr10" type="primary" v-if="detailData.showCancelButton === 1" plain @click="_isOpenCancel = true">
          撤销采购单
        </el-button>
        <el-button
          class="mr10"
          type="primary"
          @click="payApplication"
          v-if="
            detailData.needProcess &&
            (detailData.processStatus == 0 || detailData.processStatus == 2 || detailData.processStatus == 3) &&
            ![3, 9, 20, 21].includes(detailData.businessState)
          "
        >
          付款申请
        </el-button>
        <el-button
          class="mr10"
          type="primary"
          @click="applicationStatus"
          plain
          v-if="
            (detailData.processStatus == 1 || detailData.processStatus == 2 || detailData.processStatus == 3) &&
            ![3, 9, 20, 21].includes(detailData.businessState)
          "
        >
          申请状态
        </el-button>

        <el-button
          v-if="
            detailData.canEditCurrentAmount === 1 &&
            ![3, 9, 20, 21].includes(detailData.businessState) &&
            detailData.needProcess == false
          "
          class="mr10"
          type="primary"
          @click="updateCurrentAmountFun"
        >
          去支付
        </el-button>
        <div v-if="detailData.businessState == 9">
          <el-button type="" @click="handelClicDelet">删除</el-button>
        </div>
      </div>
    </div>
    <!-- 修改订单地址 -->
    <dialog-View :isShow="data.isShowAdess" :title="'修改地址'" :width="'30%'">
      <form-View
        :formList="data.formListOrderAdess"
        :rules="data.rulesOrderAdess"
        :position="'left'"
        @update="handelUpdateAdess"
        @back="handelBackAdess"
      ></form-View>
    </dialog-View>

    <!-- 撤销采购单 二次确认 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenCancel"
      :message="'订单已处于接单状态，撤销后，当前采购单将作废处理，请谨慎操作！'"
      :submitBtnText="'确认撤销'"
      @submit="returnSubmitCancel"
    />

    <!-- 订单付款计划节点明细-弹窗 -->
    <el-dialog class="plan-nodes" v-model="planNodes" title="订单付款计划节点明细" width="1200" align-center>
      <div class="plan-nodes-top">
        <div class="money-box">
          订单总额应收金额：<span class="money"> ¥{{ detailData.payableTotalAmount }}</span>
        </div>
      </div>
      <div class="timeline-wrap">
        <el-timeline class="timeline" style="margin-top: 20px">
          <el-timeline-item v-for="(item, index) in detailData.payPlanList" :key="index">
            <template #dot>
              <div class="dot">{{ item.collectionType }}期款项</div>
            </template>
            <template #default>
              <div class="default-wrap">
                <div class="default">
                  <div class="default-title">
                    <p>{{ filterBusiness(item.businessNode) }}</p>
                  </div>
                  <el-descriptions class="descriptions" :column="4">
                    <el-descriptions-item label="商家付款比例" label-class-name="my-label" class-name="my-content">
                      {{ item.collectionScale }}%
                    </el-descriptions-item>
                    <!-- <el-descriptions-item label="供应商收款节点" label-class-name="my-label" class-name="my-content">
                      {{ filterCollection(item.collectionNode) }}
                    </el-descriptions-item> -->
                    <el-descriptions-item label="平台支付时效" label-class-name="my-label" class-name="my-content">
                      {{ item.collectionCycle }}
                    </el-descriptions-item>
                    <el-descriptions-item label="计划付款日期" label-class-name="my-label" class-name="my-content">
                      {{ item.planPaymentTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="付款节点日期" label-class-name="my-label" class-name="my-content">
                      {{ item.paymentTime }}
                    </el-descriptions-item>
                    <el-descriptions-item label="计划应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.payableAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="税额" label-class-name="my-label" class-name="my-content">
                      {{ item.taxAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="实际应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.realityPayableAmount }}
                    </el-descriptions-item>
                    <el-descriptions-item label="剩余应付金额" label-class-name="my-label" class-name="my-content">
                      {{ item.surplusPayableAmount }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </template>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-dialog>

    <!-- 抽屉 -->
    <!-- 发货确认、自提货完成确认、安装完成确认、配送完成确认-->
    <editorDialog
      v-model:isOpen="_isOpenEditor"
      :title="editorDialogInfo.title"
      :status="editorDialogInfo.status"
      :remark="editorDialogInfo.remark"
      :refuseReason="editorDialogInfo.refuseReason"
      :refuseRemark="editorDialogInfo.refuseRemark"
      :submitBtnText="editorDialogInfo.submitBtnText"
      :cancelBtnText="editorDialogInfo.cancelBtnText"
      @submit="submitDrawer"
      @refuse="refuseDrawer"
      @close="closeDrawer"
    />

    <!-- 通过审核二次确认-弹窗 -->
    <el-dialog v-model="adoptDialog" title="" center align-center width="500">
      <div class="adopt-dialog">
        请仔细核对，或者致电联系，确保您的订单商品已{{ editorDialogInfo.title }}一旦确认通过后，此操作不支持逆向操作，请谨慎操作！
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="adoptDialog = false">取消</el-button>
          <el-button type="primary" @click="adoptDialogSubmit"> 确认通过 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" width="480px" title="付款申请记录">
      <div class="dialog_line"></div>
      <div class="dialog_price">
        <div class="dialog_price_item">
          <div class="dialog_pricefather">
            <div class="dialog_price_num">¥{{ detailData.remainTotalAmount }}</div>
            <div class="dialog_price_remark">未付金额</div>
          </div>
        </div>
        <div class="dialog_price_item">
          <div class="dialog_pricefather">
            <div class="dialog_price_num">¥{{ detailData.actualTotalAmount }}</div>
            <div class="dialog_price_remark">实付金额</div>
          </div>
        </div>
      </div>
      <div class="dialog_title">
        <div class="dialog_title_text">状态</div>
        <div :class="`dialog_title_status ${showPaystatus[detailData.processStatus]?.type}`">
          <div style="margin: 0 10px">{{ showPaystatus[detailData.processStatus]?.label }}</div>
        </div>
      </div>
      <div class="dialog_linecenter"></div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">采购总金额</div>
        <div class="dialog_countent_right">¥{{ detailData.payableTotalAmount }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付金额</div>
        <div class="dialog_countent_right">¥{{ detailData.currentPayableAmount }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付说明</div>
        <div class="dialog_countent_right">{{ detailData.currentPayableRemark }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付合作方</div>
        <div class="dialog_countent_right">{{ detailData.payAccountName }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">创建时间</div>
        <div class="dialog_countent_right">{{ detailData.processCreateTime }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">审核时间</div>
        <div class="dialog_countent_right">{{ detailData.processTime }}</div>
      </div>
      <!-- <div class="dialog_countent">
        <div class="dialog_countent_left">审核意见</div>
        <div class="dialog_countent_right">{{ detailData.processRemark }}</div>
      </div> -->
      <div class="dialog_foot">
        <div class="dialog_foot_left"><div @click="dialogVisible = false">取消</div></div>
        <div class="dialog_foot_right"><div @click="dialogVisible = false">确认</div></div>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogVisibletwo" width="480px" title="付款申请确认">
      <div class="dialog_line"></div>
      <div class="dialog_price">
        <div class="dialog_price_item">
          <div class="dialog_pricefather">
            <div class="dialog_price_num">¥{{ detailData.remainTotalAmount }}</div>
            <div class="dialog_price_remark">未付金额</div>
          </div>
        </div>
        <div class="dialog_price_item">
          <div class="dialog_pricefather">
            <div class="dialog_price_num">¥{{ detailData.actualTotalAmount }}</div>
            <div class="dialog_price_remark">实付金额</div>
          </div>
        </div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">采购总金额</div>
        <div class="dialog_countent_right">¥{{ detailData.payableTotalAmount }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付金额</div>
        <div class="dialog_countent_right" style="color: #ff3333">¥{{ detailData.currentPayableAmount }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付说明</div>
        <div class="dialog_countent_right">{{ detailData.currentPayableRemark }}</div>
      </div>
      <div class="dialog_countent">
        <div class="dialog_countent_left">本次应付合作方</div>
        <div class="dialog_countent_right">{{ detailData.payAccountName }}</div>
      </div>
      <div class="dialog_foot">
        <div class="dialog_foot_left" @click="dialogVisibletwo = false"><div>拒绝</div></div>
        <div class="dialog_foot_right" @click="paycommit"><div>提交</div></div>
      </div>
    </el-dialog>
    <!-- 拒绝-弹窗 -->
    <RefuseDialog v-model:isOpen="refuseDialog" :options="refuseOptions" @submit="refuseSubmit" @close="refuseClose" />
  </div>
</template>
<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  purchaseOrderId,
  getlistByTenantId,
  getTempProductSkuList,
  getProvideList,
  deleteClose,
  updateCurrentAmount,
  cancelOrder,
  getFinishConfirm,
  commitConfirm
} from "@/apis/procure/index";
import { getPayAccountList } from "@/apis/order/index";
import china from "@/utils/china.json";
const chinas = ref(china);
import { shoppingList } from "@/store/index";
const shoppingLists = shoppingList();
import { ElMessage } from "element-plus";
// 组件导入
import dialogView from "./components/dialogView.vue";
import formView from "./components/formView.vue";
import RemarkEditor from "@/components/RemarkEditor";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";

import EditorDialog from "../../components/editorDialogNew.vue";
import RefuseDialog from "../../components/refuseDialog.vue";
const isChainTenant = JSON.parse(localStorage.getItem("userinfo"))?.isChainTenant; //判断是否是加盟商
// 获取商品的数据
// 组件导入
// import dialogView from '@/components/dialogView/index.vue'
const _isOpenCancel = ref(false);
const useRout = useRouter();
const useRoutes = useRoute();
const ruleFormRef = ref();
const ruleForm = ref({});
const dialogVisible = ref(false);
const dialogVisibletwo = ref(false);

const rules = ref({
  name: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
    { min: 3, max: 5, message: "Length should be 3 to 5", trigger: "blur" }
  ]
});
const zhList = ref([]); //收款账户list
const forms = ref({});
// 底部栏的动态宽度
const footerWidth = ref(0);
// 获取dom
const my_purchase = ref();
const data = reactive({
  // 显示修改地址弹框
  isShowAdess: false,
  // 修改地址------------
  formListOrderAdess: [
    { label: "收货人", model: "receivingName", type: "input" },
    { label: "手机", model: "receivingMobile", type: "input" },
    { label: "收货地址", model: "receivingAddress", type: "cascader", options: chinas },
    { label: "详细地址", model: "receivingAreaDetail", type: "input" }
  ],
  // 修改地址规则
  rulesOrderAdess: {
    receivingName: [
      { required: true, message: "请输入名称", trigger: "blur" },
      { min: 1, max: 200, message: "请输入名称", trigger: "blur" }
    ],
    receivingMobile: [
      { required: true, message: "请输入电话", trigger: "blur" },
      { min: 1, max: 200, message: "请输入电话", trigger: "blur" }
    ],
    receivingAddress: [
      {
        required: true,
        message: "请选择地址",
        trigger: "change",
        validator: (rule, value, callback) => {
          if (value.length === 0) {
            return callback(new Error("请选择一个地址"));
          }
          return callback();
        }
      }
    ],
    receivingAreaDetail: [
      { required: true, message: "请输入详细地址", trigger: "blur" },
      { min: 1, max: 300, message: "请输入详细地址", trigger: "blur" }
    ]
  },
  totalPicAll: 0,
  // 创建采购单-------
  gcList: [], //供应商列表数据
  informationObj: {},
  // 创建采购单------end
  orderId: "",
  num: 1, //1代表普通采购单，2代表定时采购单
  totalPic: 0,
  // 清除定时
  isShowClearTime: false
  // 清除定时-------end
});

// 上传
// const FileList = ref([]); //商品图片list
const uploadImg = ref();
const PicUrls = ref([
  "https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/CRM/97c081008728f7d09014930a4a9163d3-96ad51a535f67841c8683777fe203d32398e.jpg",
  "https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/CRM/640ebb147f28ccc1d62fd5aede1e8cfa-7658bea1795330423b29cafd8fdcc9f334d1.jpg"
]);
const videoUrls = ref([
  "https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/CRM/%E6%B5%8B%E8%AF%95%E8%A7%86%E9%A2%91-f26ed260b487684bb518c38c438b73be0075.mp4",
  "https://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/CRM/bc52d30d-c452-4d19-9829-ac8bc4baf124-0b785c78db013645f3e82b0c35b1982133de.mp4"
]);
const showPaystatus = [
  {
    value: 0,
    label: "未提交",
    type: ""
  },
  {
    value: 1,
    label: "已提交",
    type: "waitpay_status"
  },
  {
    value: 2,
    label: "已通过",
    type: "success_status"
  },
  {
    value: 3,
    label: "已拒绝",
    type: "refuse_status"
  }
];
//撤销采购单-确认
const returnSubmitCancel = () => {
  cancelOrder({ purchaseOrderId: detailData.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "采购单撤销成功",
        type: "success"
      });
      _isOpenCancel.value = false;
      handelClickBack(); //返回列表页
    }
  });
};

const getcancelRejectName = type => {
  const arr = [
    { key: 1, val: "原材料已采购" },
    { key: 2, val: "订单已安排生产" },
    { key: 3, val: "部分商品已生产" },
    { key: 4, val: "其他原因" }
  ];
  const obj = arr.find(item => item.key === type);
  if (obj) {
    return obj.val;
  } else {
    return "--";
  }
};

const toProdDetail = row => {
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/designer/shopDetail/index",
    query: { id: row?.productId }
  });
  window.open(routeUrl.href, "_blank");
};

//获取支付账户列表
const zhListCopy = ref([]); //复制一份账户列表，条件筛选的时候使用
const getPayAccountListFun = () => {
  getPayAccountList({
    factoryId: detailData.value.factoryId
  }).then(res => {
    if (res.code === 200) {
      zhList.value = res.data;
      zhListCopy.value = JSON.parse(JSON.stringify(res.data));
    }
  });
};

const filterZhList = val => {
  const filterArr = zhListCopy.value.filter(item => {
    if (item.accountName?.includes(val) || item.account?.includes(val)) {
      return item;
    }
  });
  zhList.value = filterArr;
};

//修改本次应付金额
const updateCurrentAmountFun = () => {
  //获取选择的收款账户
  const selectedZhObj = zhList.value.find(item => item.partnerAccountId === detailData.value.partnerAccountId);
  const _selectedZhObj = {
    payAccountId: selectedZhObj?.partnerAccountId || "",
    payAccount: selectedZhObj?.account || "",
    payDictName: selectedZhObj?.dictName || "",
    payAccountName: selectedZhObj?.accountName || ""
  };

  const params = {
    purchaseOrderId: useRoutes.query.purchaseOrderId,
    currentPayableAmount: detailData.value.currentPayableAmount,
    ..._selectedZhObj,
    currentPayableRemark: detailData.value.currentPayableRemark
  };
  updateCurrentAmount(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "本次应付金额修改成功",
        type: "success"
      });
      handelClickBack(); //返回上一页
    }
  });
};
const paycommit = () => {
  updateCurrentAmountFun();
  dialogVisibletwo.value = false;
};
// 显示状态
const showStatus = n => {
  switch (n) {
    case 0:
      return "定时中";
    case 1:
      return "编辑中";
    case 2:
      return "待接单";
    case 3:
      return "已拒绝订单";
    case 4:
      return "待发货";
    case 5:
      return "部分待入库";
    case 6:
      return "待入库";
    case 7:
      return "部分入库";
    case 8:
      return "已入库";
    case 9:
      return "已关闭";
    case 20:
      return "已撤销";
    case 21:
      return "撤销待审核";
    default:
      "";
  }
};
const handelOnPreview = v => {
  const link = document.createElement("a");
  link.href = v.fileUrl;
  link.click();
};
// 判断不同状态的颜色
const colorStatus = n => {
  switch (n) {
    case 0:
      return ["#FF9900", "#FFF0D9"];
    case 1:
      return ["#606266", "#cdcdcd"];
    case 2:
      return ["#FF9900", "#FFF0D9"];
    case 3:
      return ["#FF3333", "#ffafaf"];
    case 4:
      return ["#FF9900", "#FFF0D9"];
    case 5:
      return ["#007DFF", "#badcff"];
    case 6:
      return ["#FF9900", "#fff2de"];
    case 7:
      return ["#007DFF", "#e5f2ff"];
    case 8:
      return ["#007DFF", "#e5f2ff"];
    case 9:
      return ["#86909C", "#e4f0ff"];
    case 10:
      return ["#FF9900", "#fff2de"];
    case 11:
      return ["#FF9900", "#fff2de"];
    case 12:
      return ["#14C85C", "#E3F9E9"];
    case 20:
      return ["#ff3333", "#E3F9E9"];
    case 21:
      return ["#FF9900", "#FFF0D9"]; //黄色
    default:
      return "";
  }
};
// 返回
const handelClickBack = () => {
  useRout.push({
    path: "/procure/purchase-order"
  });
};
// 新创建采购单----------
const getProvideLists = async () => {
  const resalt = await getProvideList({ status: 1 }, 1000, 1000);
  let arr = [];
  resalt.data.list.map(it => {
    arr.push({ label: it.bossName, value: it.factoryId });
  });
  data.gcList = arr;
};
// 已关闭----------------------
// deleteClose
const handelClicDelet = () => {
  deleteClose(useRoutes.query.purchaseOrderId)
    .then(() => {
      ElMessage({
        type: "success",
        message: "删除成功"
      });
      setTimeout(() => {
        useRout.push({
          path: "/procure/purchase-order"
        });
      }, 2000);
    })
    .catch(() => {
      ElMessage({
        type: "error",
        message: "删除失败"
      });
    });
};
// 已关闭---------------------end
const warehouseList = ref([]);
const warehouseArry = ref([]);
const warehouseObj = ref({}); //获取最后的收货数据
const getlistByTenantIds = () => {
  getlistByTenantId().then(res => {
    let arr = [];
    warehouseArry.value = res.data;
    res.data.map(it => {
      arr.push({ label: it.warehouseName, value: it.warehouseId });
    });
    warehouseList.value = arr;
  });
};
const handelUpdateAdess = (item, address) => {
  detailData.value.receivingName = item.receivingName;
  detailData.value.receivingMobile = item.receivingMobile;
  detailData.value.receivingAreaDetail = address + item.receivingAreaDetail;
  detailData.value.receivingAreaIds = item.receivingAddress.join(",");
  data.isShowAdess = false;
};
const handelBackAdess = () => {
  data.isShowAdess = false;
};
const handelChangePutAway = v => {
  warehouseArry.value.map(it => {
    if (v === it.warehouseId) {
      detailData.value.receivingName = it.warehouseName;
      detailData.value.receivingMobile = it.managePhoneNo;
      detailData.value.receivingAreaDetail = it.provinceName + it.cityName + it.districtName + it.address;
    }
  });
};
// 新建采购单添加到缓存的数据
const tabelList = ref([]);
const copyTabelList = ref();
const getTempProductSkuLists = () => {
  getTempProductSkuList({ code: useRoutes.query.code, businessId: JSON.parse(localStorage.getItem("userinfo")).tenantId })
    .then(res => {
      // 添加字段  则扣金额，则扣率
      res.data.map(it => {
        it.discountAmount = 0; //则扣金额
        it.discountRate = 0; //则扣率
        it.commodityNum = 1; //订单商品数量
        if (it.partNum == null) {
          it.partNum = 0;
        }
      });
      let copyDate = JSON.stringify(res.data);
      copyTabelList.value = JSON.parse(copyDate);
      tabelList.value = res.data;
    })
    .catch(err => {});
};

const handelInputs = e => {};
// 新创建采购单----------end
// 查询详情---------
const detailData = ref({});
// 附件
const imgFileList = ref([]);
const getDetails = async () => {
  await purchaseOrderId(useRoutes.query.purchaseOrderId).then(res => {
    res.data.receivingType = res.data.receivingType.toString();
    detailData.value = res.data;
    console.log(detailData.value);

    detailData.value.partnerAccountId = res.data.payAccountId;

    // 发票附件
    if (res.data.uploadInvoiceUrls) {
      detailData.value.uploadInvoiceUrls = res.data.uploadInvoiceUrls.split(",");
    }
    let num = 0;
    // 支持开票-取开票的税率，不支持取0
    if (detailData.value.isSupportBilling == 1) {
      if (detailData.value.invoiceType == 1) {
        num = Number(detailData.value.specialTicket || 0);
      } else {
        num = Number(detailData.value.ordinaryTicket || 0);
      }
    }
    // 小数点2位 *1000 避免长度失真
    detailData.value.feeAmount = (((detailData.value.payableTotalAmount * 1000) / 100) * num * 1000) / 1000000;
    // 回显附件
    const imgFileListArr = res.data.attachmentFileUrls;
    const newFiles = imgFileListArr.length > 0 ? imgFileListArr.split(",") : [];
    const reslatFileArr = [];
    newFiles.map(it => {
      reslatFileArr.push({
        url: it,
        fileUrl: it,
        name: decodeURI(it).split("/")[decodeURI(it).split("/").length - 1]
      });
    });
    imgFileList.value = reslatFileArr;

    // 回显tebs标签信息
    if (detailData.value.installConfirmInfo) {
      activeName.value = 1;
    } else if (detailData.value.produceConfirmInfo) {
      activeName.value = 2;
    } else if (detailData.value.distributeConfirmInfo) {
      activeName.value = 3;
    } else if (detailData.value.selfPickupConfirmInfo) {
      activeName.value = 4;
    } else {
      activeName.value = null;
    }
    handleClick(activeName.value);
  });
};

// 查询详情---------end
onMounted(async () => {
  getProvideLists();
  getlistByTenantIds();
  if (useRoutes.query.num == 1 && useRoutes.query.code !== undefined) {
    getTempProductSkuLists();
    // 新建采购单回显数据
    ruleForm.value = shoppingLists.productInformation.ruleForm;
    forms.value = shoppingLists.productInformation.forms;
    warehouseList.value = shoppingLists.productInformation.warehouseList;
    warehouseObj.value = shoppingLists.productInformation.warehouseObj;
    data.informationObj = shoppingLists.productInformation.informationObj;
  }
  //  走详情页面
  await getDetails();

  getPayAccountListFun(); //获取收款账户信息list
  // 初始化地址数据
  chinas.value.map(item => {
    // 第一层
    item.label = item.name;
    item.value = item.cityCode;
    if (item.hasOwnProperty("children")) {
      // 第二层
      item.children.map(citem => {
        citem.label = citem.name;
        citem.value = citem.cityCode;
        // eslint-disable-next-line no-prototype-builtins
        if (citem.hasOwnProperty("children")) {
          // 第三层
          citem.children.map(ccitem => {
            ccitem.label = ccitem.name;
            ccitem.value = ccitem.cityCode;
          });
        }
      });
    }
  });
  // 获取dom元素给底部操作栏设置动态宽度
  if (my_purchase.value) {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        footerWidth.value = entry.contentRect.width;
      }
    });

    resizeObserver.observe(my_purchase.value);
    // 组件卸载时取消监听
    onUnmounted(() => {
      resizeObserver.disconnect();
    });
  }
});

// 业务信息
const operationFlowInfo = ref({});
const activeName = ref(1);
const handleClick = value => {
  switch (value) {
    case 1:
      operationFlowInfo.value = detailData.value.installConfirmInfo;
      break;
    case 2:
      operationFlowInfo.value = detailData.value.produceConfirmInfo;
      break;
    case 3:
      operationFlowInfo.value = detailData.value.distributeConfirmInfo;
      break;
    case 4:
      operationFlowInfo.value = detailData.value.selfPickupConfirmInfo;
      break;
    default:
      operationFlowInfo.value = null;
      break;
  }
};

// 付款计划节点明细-弹窗
const planNodes = ref(false);
const openPlanNodes = () => {
  planNodes.value = true;
};

// 业务流程操作类别
const operationFlowType = ref(0);
const handleProduction = type => {
  operationFlowType.value = type;
  getFinishConfirmApi();
};

const editorDialogInfo = ref({});

// 获取完成确认信息
const getFinishConfirmApi = async () => {
  const res = await getFinishConfirm({ purchaseOrderId: detailData.value.purchaseOrderId, type: operationFlowType.value });
  editorDialogInfo.value = res.data;
  switch (operationFlowType.value) {
    case 1:
      editorDialogInfo.value.title = "发货确认";
      refuseOptions.value = ["没有技照要求生产", "只完成了部份生产", "没有生产完成", "虚假提交生产完成确认", "其他原因"];
      break;
    case 2:
      editorDialogInfo.value.title = "配送完成确认";
      refuseOptions.value = ["没有按照地址配送", "没有收到商品", "收到部分商品", "虚假提交配送完成", "其他原因"];
      break;
    case 3:
      editorDialogInfo.value.title = "自提货完成确认";
      refuseOptions.value = ["只提取部分产品货物", "没有提货", "货物还没有达到", "虚假提交提货确认", "其他原因"];
      break;
    case 4:
      editorDialogInfo.value.title = "安装完成确认";
      refuseOptions.value = ["没有完成安装", "部分安装", "全部没有安装", "虚假提交安装完成确认", "其他原因"];
      break;
    default:
      break;
  }
  editorDialogInfo.value.titleTips = "等待确认审核";
  editorDialogInfo.value.submitBtnText = "通过";
  editorDialogInfo.value.cancelBtnText = "拒绝";
  _isOpenEditor.value = true;
};

// 通过审核二次确认-弹窗
const adoptDialog = ref(false);
const adoptDialogSubmit = async () => {
  await commitConfirmApi(1);
  adoptDialog.value = false;
  closeDrawer();
};

// 拒绝-弹窗
const refuseDialog = ref(false);
// 拒绝原因
const refuseOptions = ref([]);
// 拒绝弹窗-提交
const refuseSubmit = async value => {
  await commitConfirmApi(0, value.refuseReason, value.refuseRemark);
  await getFinishConfirmApi();
  refuseClose();
};
const refuseClose = () => {
  refuseDialog.value = false;
};

// 抽屉
// 生产完成确认、已完成提货、安装完成确认、配送完成确认
const _isOpenEditor = ref(false);
// 抽屉-通过
const submitDrawer = () => {
  adoptDialog.value = true;
};
// 抽屉-拒绝
const refuseDrawer = () => {
  refuseDialog.value = true;
};
// 抽屉-关闭
const closeDrawer = () => {
  _isOpenEditor.value = false;
};

// 提交完成确认信息
const commitConfirmApi = async (opinion, refuseReason, refuseRemark) => {
  await commitConfirm({
    purchaseOrderId: detailData.value.purchaseOrderId,
    type: operationFlowType.value,
    opinion,
    refuseReason,
    refuseRemark
  }).then(() => {
    if (opinion == 1) {
      ElMessage.success("审核通过");
    }
    getDetails();
  });
};

const filterCollection = value => {
  let name = "";
  switch (value) {
    case 1:
      name = "接采购单即付款";
      break;
    case 2:
      name = "生产完成确认";
      break;
    case 3:
      name = "发货完成";
      break;
    case 4:
      name = "入库确认";
      break;
    case 5:
      name = "配送完成确认";
      break;
    case 6:
      name = "安装完成确认";
      break;
    default:
      name = "-";
      break;
  }
  return name;
};

const filterBusiness = value => {
  let name = "";
  switch (value) {
    case 1:
      name = "接单付款";
      break;
    case 2:
      name = "生产完成确认";
      break;
    case 3:
      name = "已发货";
      break;
    case 4:
      name = "入库完成";
      break;
    case 5:
      name = "配送完成";
      break;
    case 6:
      name = "安装完成";
      break;
    default:
      name = "-";
      break;
  }
  return name;
};
const payApplication = () => {
  dialogVisibletwo.value = true;
};
const applicationStatus = () => {
  dialogVisible.value = true;
};
</script>
<style scoped lang="scss">
@import "./index.scss";
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.picUrls_flex_countent {
  display: flex;
  flex-grow: 1;
  /* 占据剩余空间 */
  flex-wrap: wrap;
  flex-direction: row;
  margin-top: 10px;
}
.show-video {
  width: 69px;
  height: 64px;
}
</style>
